package cn.qiyu5522.tk_ems.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.qiyu5522.tk_ems.entity.Permission;
import cn.qiyu5522.tk_ems.entity.Role;
import cn.qiyu5522.tk_ems.entity.RolePermission;
import cn.qiyu5522.tk_ems.entity.UserRole;
import cn.qiyu5522.tk_ems.entity.dto.QueryParamDTO;
import cn.qiyu5522.tk_ems.entity.dto.RoleDTO;
import cn.qiyu5522.tk_ems.entity.vo.RoleVO;
import cn.qiyu5522.tk_ems.mapper.RoleMapper;
import cn.qiyu5522.tk_ems.result.CustomMapResult;
import cn.qiyu5522.tk_ems.result.R;
import cn.qiyu5522.tk_ems.service.PermissionService;
import cn.qiyu5522.tk_ems.service.RolePermissionService;
import cn.qiyu5522.tk_ems.service.RoleService;
import cn.qiyu5522.tk_ems.service.UserRoleService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Tonkey
 * @since 2023-02-22
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {
    @Resource
    private UserRoleService userRoleService;
    @Resource
    private RolePermissionService rolePermissionService;
    @Resource
    private PermissionService permissionService;
    @Resource
    private ObjectMapper objectMapper;

    @Override
    public List<Role> listRolesByUserId(Long userId) {
        // 根据用户编号查询，该用户的角色
        LambdaQueryWrapper<UserRole> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ObjectUtils.isNotEmpty(userId), UserRole::getUserId, userId);
        List<UserRole> userRoles = userRoleService.list(lambdaQueryWrapper);
        if(userRoles.size() == 0){
            return new ArrayList<>(0);
        }
        // 获取该登录用户的所拥有的角色编号
        List<Integer> roleIds = userRoles.stream().map(UserRole::getRoleId).collect(Collectors.toList());
        // 根据角色编号查询角色信息
        return baseMapper.selectBatchIds(roleIds);
    }

    @Override
    public List<Permission> listPermissionsByRoleId(Integer roleId) {
        LambdaQueryWrapper<RolePermission> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ObjectUtil.isNotEmpty(roleId), RolePermission::getRoleId, roleId);
        List<RolePermission> list = rolePermissionService.list(lambdaQueryWrapper);
        if(list.size()==0){
            return new ArrayList<>(0);
        }
        List<Integer> permissionIds = list.stream().map(RolePermission::getPermissionId).collect(Collectors.toList());

        return permissionService.listByIds(permissionIds);
    }


    @Override
    public R queryRoleListByCondition(QueryParamDTO<RoleDTO> queryParamDTO) {
        IPage<Role> roleIPage = new Page<>(queryParamDTO.getCurrentPage(),queryParamDTO.getPageSize());
        RoleDTO condition = queryParamDTO.getCondition();
        LambdaQueryWrapper<Role> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ObjectUtil.isNotEmpty(condition.getId()),Role::getId,condition.getId());
        lambdaQueryWrapper.like(ObjectUtil.isNotEmpty(condition.getDescription()),Role::getDescription,condition.getDescription());
        baseMapper.selectPage(roleIPage,lambdaQueryWrapper);
        // 实体转VO
        List<RoleVO> roleVOS = objectMapper.convertValue(roleIPage.getRecords(), new TypeReference<List<RoleVO>>() {
        });
        Map<String, Object> map = CustomMapResult.packagingResult(
                roleVOS,
                queryParamDTO.getCurrentPage(),
                queryParamDTO.getPageSize(),
                roleIPage.getTotal()
        );
        return R.ok().data("roleIPage",map);
    }

    @Override
    public R saveMore(List<RoleDTO> roleDTOs) {
        List<Role> roles = objectMapper.convertValue(roleDTOs, new TypeReference<List<Role>>() {
        });
        Integer integer = baseMapper.insertBatchSomeColumn(roles);
        return integer.compareTo(0)>0? R.ok().message("添加成功"):R.error().message("添加失败");
    }
}
